package arm.mbean;

import java.rmi.AccessException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.log4j.Logger;

public class ArmRegistry {

	private static final Logger log = Logger.getLogger(ArmRegistry.class);
	private int rmiport;
	private String host;
	private Registry registry;

	public Registry createRegistry() throws RemoteException {

		if (host != null) {
			try {
				registry = LocateRegistry.getRegistry(host, rmiport);
				this.testRegistry(registry);
			} catch (RemoteException e) {
				try {
					log.info("look up host:"+host+" registry rmi server but server is not create");
					registry = LocateRegistry.getRegistry(rmiport);
					testRegistry(registry);
				} catch (RemoteException e1) {
					registry = LocateRegistry.createRegistry(rmiport);
					log.info("look up rmiport:"+rmiport+" rmi server but server is not create,create one instance");
				}
			}
		}
		else
		{
			if(rmiport!=0)
			{
				try{
				registry = LocateRegistry.getRegistry(rmiport);
				testRegistry(registry);
				}catch(Exception e)
				{
					registry = LocateRegistry.createRegistry(rmiport);
					log.info("look up rmiport:"+rmiport+" rmi server but server is not create,create one instance");
				}
			}
			else
			{
				log.info("not found rmi properties configuration");
			}
		}
		return registry;
	}

	private void testRegistry(Registry registry) throws AccessException,
			RemoteException {
		registry.list();
	}

	public void setRmiport(int rmiport) {
		this.rmiport = rmiport;
	}

	public void setHost(String host) {
		this.host = host;
	}

	
}
